#!/bin/sh

# Copyright 2019-2021 Balena Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# OpenSSH is configured to pass to AuthorizedKeysCommand the username as the
# first argument
_username="$1"
shift

# shellcheck disable=SC1091
. /usr/sbin/balena-config-vars
 _api_key="$DEVICE_API_KEY"
 _api_endpoint="$API_ENDPOINT"

if [ -z "$_api_endpoint" ] || [ -z "$_api_key"  ] || [ -z "$_username" ]; then
	exit 1
fi

# We short circuit the 'root' user to always be used as a local account
[ "$_username" = "root" ] && exit 0

# Get the user public ssh key from the API
curl -H "Authorization: Bearer ${_api_key}" "$_api_endpoint/auth/v1/public-keys/$_username"
